import 'dart:io';
import 'dart:typed_data';

import 'package:collection/collection.dart';
import 'package:excel/excel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/GoodsApi.dart';
import 'package:flutter_2b_client/components/LoadingButton.dart';
import 'package:flutter_2b_client/database/entity/GoodsScratchItem.dart';
import 'package:flutter_2b_client/pages/GoodsPage.dart';
import 'package:flutter_2b_client/utils/ExcelUtils.dart';
import 'package:flutter_2b_client/utils/ShareUtils.dart';
import 'package:flutter_2b_client/utils/ToastUtils.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

import '../components/showConfirmDialog.dart';
import '../database/AppDatabase.dart';
import '../theme/custom_color.dart';
import '../utils/DeviceStorageUtils.dart';
import '../utils/UIConstant.dart';

class GoodsScratchDetailPage extends HookWidget {
  final int id;

  const GoodsScratchDetailPage({Key? key, required this.id}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var dataState = useState<List<GoodsScratchItem>>([]);
    query() async {
      var appDatabase = (await AppDatabase.instance);
      var goodsScratchItemDao = appDatabase.goodsScratchItemDao;
      dataState.value = await goodsScratchItemDao.findPageByGoodsScratchId(id);
    }

    useEffect(() {
      query();
    }, []);
    var scrollController = useScrollController();

    return Scaffold(
      appBar: AppBar(
        title: const Text("商品草稿单"),
        actions: [
          PopupMenuButton(
            onSelected: (value) async {
              var fileBytes = exportGoodsToExcel(dataState.value
                  .map((e) => GoodsRow(
                      name: e.name,
                      barcode: e.barcode,
                      price: e.price,
                      amount: e.amount))
                  .toList());
              if (fileBytes == null) {
                if (context.mounted) {
                  showErrorToast(context, "生成excel失败");
                }
                return;
              }
              final name = "商品草稿$id.xlsx";
              if (value == 1) {
                saveFileBytes(context,name,fileBytes);
              } else if (value == 2) {
                shareExcelFileByBytes(context, fileBytes, name);
              }
            },
            itemBuilder: (BuildContext context) => [...shareAndExportMenuEntries]
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () async {
          final result =
              await context.push(Uri(path: "/goods", queryParameters: {
            "multiSelect": true.toString(),
            "returnItem": true.toString(),
            "excludeIds": dataState.value
                .map((e) => e.goodsId.toString())
                .toList()
                .join(","),
          }).toString()) as List<GoodsBasic>;
          if (result.isNotEmpty) {
            var list = dataState.value.toList();
            for (var e in result) {
              var appDatabase = (await AppDatabase.instance);
              var goodsScratchItemDao = appDatabase.goodsScratchItemDao;
              var goodsScratchItem = GoodsScratchItem(
                  null, e.name, e.barcode, id, e.price, e.amount, e.id);
              var itemId = await goodsScratchItemDao
                  .insertGoodsScratchItem(goodsScratchItem);
              list.add(goodsScratchItem..id = itemId);
            }
            scrollController.jumpTo(64.0 * list.length);
            dataState.value = list;
          }
        },
      ),
      body: ListView(
        controller: scrollController,
        children: dataState.value.map(
          (item) {
            return GestureDetector(
              key: Key(item.goodsId.toString()),
              onLongPress: () {
                showConfirmDeleteGoodsDialog(
                  context,
                  barcode: item.barcode,
                  name: item.name,
                  onConfirm: () async {
                    var appDatabase = (await AppDatabase.instance);
                    var goodsScratchItemDao = appDatabase.goodsScratchItemDao;
                    await goodsScratchItemDao.deleteGoodsScratchItem(item);
                    dataState.value = dataState.value.toList()..remove(item);
                    if (context.mounted) {
                      Navigator.of(context).pop();
                    }
                  },
                );
              },
              child: GoodsListItem(
                GoodsBasic(
                  id: item.goodsId,
                  name: item.name,
                  barcode: item.barcode,
                  price: item.price,
                  amount: item.amount,
                ),
                onPressed: (){
                  context.push("/goods/${item.goodsId}");
                },
              ),
            );
          },
        ).toList(),
      ),
    );
  }
}
